package com.example.stlink.activitys.fragmentChild.activityTeaCourse;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;

import com.example.stlink.R;
import com.example.stlink.fragments.CourseClassListFragment;
import com.example.stlink.fragments.CourseIntroMsgFragment;
import com.example.stlink.fragments.CourseSelectedStuFragment;
import com.example.stlink.model.constants.ModelFieldConstants;
import com.example.stlink.model.constants.UrlConstants;
import com.example.stlink.model.response.BaseResponse;
import com.example.stlink.model.response.data.CourseDetailData;
import com.example.stlink.utils.CommonUtils;
import com.example.stlink.utils.activityUtil.CourseDetailUtil;
import com.example.stlink.utils.httpUtils.GetUrlParamHttpUtils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.internal.LinkedTreeMap;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.List;

public class CourseDetail extends AppCompatActivity {

    private ImageView abIvTitle;
    private TextView abTvCourseName;
    private TextView abTvCollegeName;
    private TextView abTvTeacherName;
    private TextView abTvCourseIdMsg;

    private Integer position;

    CourseDetailUtil courseDetailUtil;

    private Bundle bundle;
    private Handler handler;

    private CourseDetailData mCourseDetailData;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_course_detail);

        initView();

        initPager();

    }

    private void initView(){
        //修改状态栏字体颜色
        CommonUtils.changeStatusBar(this);

        abIvTitle = findViewById(R.id.ab_iv_title);
        abTvTeacherName = findViewById(R.id.ab_tv_teacher_name);
        abTvCollegeName = findViewById(R.id.ab_tv_college_name);
        abTvCourseName = findViewById(R.id.ab_tv_course_name);
        abTvCourseIdMsg = findViewById(R.id.ab_tv_course_id_msg);

        courseDetailUtil = new CourseDetailUtil(this);
        courseDetailUtil.initView();

        setListener();

        refreshData();

    }

    private void refreshData(){
        bundle = getIntent().getExtras();

        handler = new Handler(Looper.getMainLooper()){
            @SuppressLint("NotifyDataSetChanged")
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
                if(msg.arg1 == 200){
                    CourseDetailData courseDetailData = (CourseDetailData) msg.obj;
                    mCourseDetailData = courseDetailData;
                    String courseName = courseDetailData.getCourseName();
                    String collegeName = courseDetailData.getCollegeName();
                    String teacherName = courseDetailData.getRealName();
                    Long idMsg = courseDetailData.getId();
                    if(teacherName != null){
                        abTvTeacherName.setText(teacherName);
                    }
                    if(collegeName != null){
                        abTvCollegeName.setText(collegeName);
                    }
                    if(courseName != null){
                        abTvCourseName.setText(courseName);
                    }
                    if(idMsg != null){
                        abTvCourseIdMsg.setText(String.valueOf(idMsg));
                    }
                    bundle = getIntent().getExtras();
                    bundle.putSerializable(ModelFieldConstants.COURSE_DETAIL_DATA, mCourseDetailData);
                    getIntent().putExtras(bundle);
                    //在网路请求成功后，回调进行加载数据
                    CourseIntroMsgFragment.freshData(getIntent());
                }else{
                    System.out.println("msg = " + msg.obj.toString());
                }
            }
        };
        getCourseDetail();
    }

    /**
     * 设置返回键点击事件
     */
    private void setListener(){
        abIvTitle.setOnClickListener(v -> finish());
    }

    private void initPager(){
        List<Fragment> list = new ArrayList<>();
        CourseIntroMsgFragment courseIntroMsgFragment = CourseIntroMsgFragment.newInstance("课程简介", CourseDetail.this);
        CourseClassListFragment courseClassListFragment = CourseClassListFragment.newInstance("班级列表", CourseDetail.this);
        CourseSelectedStuFragment courseSelectedStuFragment = CourseSelectedStuFragment.newInstance("选课学生", CourseDetail.this);
        list.add(courseIntroMsgFragment);
        list.add(courseClassListFragment);
        list.add(courseSelectedStuFragment);
        courseDetailUtil.initPage(list);
    }

    private void getCourseDetail(){
        new Thread(() -> {

            long courseId = bundle.getLong(ModelFieldConstants.COURSE_ID);
            long userId = bundle.getLong(ModelFieldConstants.USER_ID);

            String urlParam = ModelFieldConstants.COURSE_ID + "=" + courseId + "&" +
                    ModelFieldConstants.USER_ID + "=" + userId;
            String url = UrlConstants.COURSE_DETAIL + "?" + urlParam;

            new GetUrlParamHttpUtils() {
                @Override
                public void nextMethod(BaseResponse<Object> baseResponse) {

                    //解析数据
                    Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create();
                    Object obj = baseResponse.getData();
                    LinkedTreeMap<String, String> courseDetailMap = null;
                    if(obj instanceof LinkedTreeMap){
                        courseDetailMap = (LinkedTreeMap<String, String>) obj;
                    }
                    //将LinkedTreeMap中字段映射到User类中
                    String jsonString = gson.toJson(courseDetailMap);
                    CourseDetailData courseDetail = gson.fromJson(jsonString, new TypeToken<CourseDetailData>() {}.getType());
                    System.out.println("courseDetail = " + courseDetail + "..................");
                    Message message = new Message();
                    message.obj = courseDetail;
                    message.arg1 = 200;
                    handler.sendMessage(message);
                }
                @Override
                public void failedMethod(BaseResponse<Object> baseResponse) {
                    Message message = new Message();
                    message.obj = baseResponse.getMsg();
                    message.arg1 = baseResponse.getCode();
                    handler .sendMessage(message);
                }
            }.getConnect(url);
        }).start();
    }
}
